//
//  coredata.swift
//  iKinds
//
//  Created by kinds on 2016/11/14.
//  Copyright © 2016年 Razeware LLC. All rights reserved.
//

import Foundation
import CoreData

extension ContainerViewController{
	
	func insertKsMain(ks:KsMain){
		do{
			try ks.validateForInsert()
            //managedObjectContext.insert(ks)
			//try? ks.managedObjectContext?.save()
			//saveContext()
		}catch{
			//managedObjectContext.reset()
			if ks.isInserted{
				managedObjectContext.delete(ks)
			}
			print(error.localizedDescription)
		}
	}
	
	func deleteDBFiles(){
		let url = getDocumentsDirectory()
		print(url)
		let dbName = "ks.sqlite"
		let fm = FileManager.default
		
		do{
			try fm.removeItem(at: url.appendingPathComponent(dbName))
			try fm.removeItem(at: url.appendingPathComponent("\(dbName)-shm"))
			try fm.removeItem(at: url.appendingPathComponent("\(dbName)-wal"))
		}catch let err{
			print("Delete DB Failed : \(err.localizedDescription)")
		}
	}
	
	func testInsertFbFor(ks:KsMain){
		for i in 1...10{
			if let fb = NSEntityDescription.insertNewObject(forEntityName: "KsFeedback", into: managedObjectContext) as? KsFeedback{
				let beginDate = ks.dateBegin
				fb.date = Date(timeInterval: 60 * 60 * 24 * TimeInterval(i), since: beginDate!)
				fb.isException = false
				fb.result = true
				fb.text = "b/b/b/b"
				
				ks.addToFeedbacks(fb)
			}
		}
		saveContext()
	}
	
	func testInsertKs(){
		for i in 0...3{
			if let ks = NSEntityDescription.insertNewObject(forEntityName: "KsMain", into: managedObjectContext) as? KsMain{
				ks.type = KsMain.type.targeted.rawValue.name
				ks.title = "title \(i)"
				ks.text = "rule \(i).0\nrule \(i).1"
				ks.signature = "坎道斯"
				ks.result = false
				ks.level = 1
				ks.ktrlTimeUnit = KsMain.timeUnit.perDay.rawValue
				ks.id = Int32(i)
				ks.exception = "none"
				ks.difficulty = KsMain.difficulty.easy.rawValue
				ks.classify = "日常"
				ks.dateBegin = Date()
				ks.dateEnd = Date(timeIntervalSinceNow: 60*60*24*30)
				testInsertFbFor(ks: ks)
			}
		}
		
		saveContext()
	}
	
	func getFeedbackFor(ks:KsMain)->[KsFeedback]?{
		//return ks.feedbacks?.allObjects as? [KsFeedback]
        
        
        
		let fetchRequest:NSFetchRequest<KsFeedback> = KsFeedback.fetchRequest()
		fetchRequest.predicate = NSPredicate(format: "main == %@", ks)
		let sort = NSSortDescriptor(key: "date", ascending: false)
		fetchRequest.sortDescriptors = [sort]
		do{
			let result = try managedObjectContext.fetch(fetchRequest)
			return result
		}catch let err{
			print("get FBs failed : \(err.localizedDescription)")
			return nil
		}
	}
	
	func getSavedKsMains()->[KsMain]?{
        
		let fetch = NSFetchRequest<KsMain>(entityName:"KsMain")
		let sort = NSSortDescriptor(key: "dateBegin", ascending: true)
		fetch.sortDescriptors = [sort]
		
		fetch.predicate = commitPredicate
		do{
			let ksAry = try managedObjectContext.fetch(fetch)
			print("***** total \(ksAry.count) ks *****")
			return ksAry
		}catch let err{
			print("Fetch KsMain failed : \(err.localizedDescription)")
			return nil
		}
	}
	
	func saveContext(){
		if managedObjectContext.hasChanges{
			do{
				try managedObjectContext.save()
			}catch let err{
				print("Save Failed : \(err.localizedDescription)")
			}
		}
	}
	
	func initCoreData(){
		let modelURL = Bundle.main.url(forResource: "kinds", withExtension: "momd")!
		let managedObjectModel = NSManagedObjectModel(contentsOf: modelURL)!
		
		let coordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
		let url = getDocumentsDirectory().appendingPathComponent("ks.sqlite")
		do{
			try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: [NSMigratePersistentStoresAutomaticallyOption:true,NSInferMappingModelAutomaticallyOption:true])
			managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
			managedObjectContext.persistentStoreCoordinator = coordinator
			managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
		}catch let err{
			print("Failed to init CoreData : \(err.localizedDescription)")
			return
		}
	}
}
